package com.cdm.beans.user;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import net.sf.frails.JSFHelper;
import net.sf.frails.aop.annotations.InjectBean;
import net.sf.frails.bean.annotations.DefMbean;
import net.sf.frails.bean.annotations.InVar;
import net.sf.frails.bean.annotations.PreRender;
import net.sf.frails.bean.annotations.Prop;

import com.cdm.domain.dao.ContentDAO;
import com.cdm.domain.service.SequenceService;
import com.cdm.domain.service.SequenceServiceImpl;
import com.cdm.domain.service.Service;
import com.cdm.domain.service.ServiceImpl;
import com.cdm.persistence.Content;
import com.cdm.persistence.ContentState;
import com.cdm.persistence.ContentUse;
import com.cdm.persistence.ContentUseId;
import com.cdm.persistence.EntityManagerHelper;
import com.cdm.persistence.User;
import com.cdm.util.Constants;
import com.vivo.util.DTool;

@DefMbean
public class SpContentInfoBean {

	@Prop
	User loginUser;

	@Prop
	List<Content> contents;
	@InVar
	Content content;

	@SuppressWarnings("unchecked")
	@PreRender(failOutcome = "/user/cpContentInfo")
	public boolean init() {
		Object object = JSFHelper.getFromApplication(Constants.LOGIN_USER_KEY);
		if (object instanceof User && object != null) {
			loginUser = (User) object;
		}

		contents = EntityManagerHelper.getEntityManager().createQuery("from Content").getResultList();

		DTool.d.debug("Enter CDM Home Page");
		return true;
	}

	@InjectBean
	public String buy() {
		try {
			EntityManagerHelper.beginTransaction();
//			ContentState s = content.getContentState();
			// if (s == null) {
			// s = new ContentState(content.getDcid(), ContentState.ENCRYPTED);
			// content.setContentState(s);
			// } else {
			// s.setContentState(ContentState.ENCRYPTED);
			// }
			
			ContentUse cu = new ContentUse(new ContentUseId(sequenceService.getSequence("countentuse11"), content.getDcid(), loginUser
			        .getUserId()), new Date(System.currentTimeMillis()), 0l, new Date(System.currentTimeMillis()));
			
//			s.setEncryptTime(new Timestamp(System.currentTimeMillis()));
//			s.setEncryptCount(s.getEncryptCount() + 1);

			EntityManagerHelper.getEntityManager().persist(cu);
			EntityManagerHelper.commit();
		} catch (Exception ex) {
			ex.printStackTrace();
			EntityManagerHelper.rollback();
		}
		JSFHelper.setExpressionValue("contentDecrypt.content", this.content);
		return "/user/spContentInfoJie";
	}

	private SequenceService sequenceService = new SequenceServiceImpl();
	private Service service = new ServiceImpl();
	private ContentDAO contentDAO = new ContentDAO();

}
